package com.gamefx.engine1.display
{
	import com.gamefx.engine1.consts.ActionConst;
	import com.gamefx.engine1.consts.DirectionConst;
	import com.gamefx.utils.ArrayEx;
	
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.geom.Matrix;

	public class BitmapClipData
	{
		private static var matrix:Matrix = new Matrix();

		/**
		 * Bitmap序列帧标签信息
		 * labels.proxy["action#direction"] = BMFLabel
		 * 
		 * @see com.gamefx.engine1.core.BMFLabel
		 */
		public var labels:ArrayEx;
		
		/**
		 * 经过解析后得到的BitmapData序列
		 * bitmaps["action#direction"][frame] = [x,y,w,h] | BitmapData | null
		 */
		public var bitmaps:Object;
		
		/**
		 * 经裁剪后的bitmap的左上角相对于原MovieClip的位置
		 */
		public var offsetX:Number = 0;
		public var offsetY:Number = 0;

		/**
		 * 数据是否准备完毕
		 */
		public var ready:Boolean;
		
		/**
		 * 源url
		 */
		public var url:String;
		
		/**
		 * 源MovieClip
		 */
		public var source:MovieClip;
		
		/**
		 * 记录尚未绘制的帧数，当值为0时，清除source的引用
		 */
		public var remaining:int;
		
		
		public function BitmapClipData()
		{
		}
		
		/**
		 * 获取动作的总帧数
		 * @param action
		 * @param direction
		 * @return
		 */
		public function getTotalFrames(action:String, direction:int = DirectionConst.E):int
		{
			var labelName:String = action + "#" + direction;
			
			if (labels == null || !labels.proxy.hasOwnProperty(labelName))
			{
				return NaN;
			}
			
			return (labels.proxy[labelName] as BMFLabel).totalFrames;
		}
		
		/**
		 * 获取帧内容
		 * @param action
		 * @param direction
		 * @param frame
		 * @return null:空白帧, bitmapData:帧图像
		 */ 
		public function getContent(action:String = ActionConst.ACTION_MOTION, direction:int = DirectionConst.E, frame:int = 0):*
		{
			var labelName:String = action + "#" + direction;
			
			if (bitmaps == null || !bitmaps.hasOwnProperty(labelName) || !bitmaps[labelName].hasOwnProperty(frame))
			{
				return null;
			}
			
			var bitmatData:* = bitmaps[labelName][frame];

			//如果需要边播放边转换(只有经过BMFBuilder处理过的SWF才可以)
			if (bitmatData != null && !(bitmatData is BitmapData))
			{
				matrix.tx = -bitmatData.x;
				matrix.ty = -bitmatData.y;
				
				var temp:BitmapData = new BitmapData(bitmatData.w, bitmatData.h, true, 0x00000000);
				source.gotoAndStop((labels.proxy[labelName] as BMFLabel).frame + frame);
				temp.draw(source, matrix);
				bitmatData = bitmaps[labelName][frame] = temp;
				
				remaining--;
				if (remaining <= 0)
				{
					source = null;
				}
			}
			
			return bitmatData;
		}
	}
}